﻿using System.Collections;
using UnityEngine;

public class AnimateMaterialChange : MonoBehaviour
{
	private Material[] original;

	private IEnumerator changeEnumerator = null;

	public Material Target { get; set; }
	public float Time { get; set; }

	private void Start()
	{
		original = renderer.materials;
	}

	public void Change()
	{
		try
		{
			if (gameObject == null)
			{
				Debug.LogError("AnimateMaterialChange  return   gameobject null");
				return;
			}
			if (gameObject.activeSelf == false)
				return;
			if (changeEnumerator != null)
				StopCoroutine(changeEnumerator);

			changeEnumerator = ChangeCoroutine();

			StartCoroutine(changeEnumerator);
		}
		catch (System.Exception e)
		{
			Debug.LogException(e);
		}
	}

	private IEnumerator ChangeCoroutine()
	{
		var targetList = new Material[original.Length];

		for (int i = 0; i < targetList.Length; i++)
			targetList[i] = Target;

		renderer.materials = targetList;

		yield return new WaitForSeconds(Time);

		renderer.materials = original;
	}
}
